package com.luxf.base.domainevent.eventtype;

import com.luxf.base.domainevent.utils.DomainEventUtils;
import org.apache.commons.collections4.BidiMap;
import org.apache.commons.collections4.bidimap.DualHashBidiMap;

/**
 * 简单类型加载器
 *
 * @author fast66
 * 2021-06-29 15:02
 **/
public class SimpleEventTypeLoader implements EventTypeLoader {

    /**
     * 双向map
     * key和value都不能重复,重复以最后一次设置生效
     */
    private final BidiMap<Object, Object> bidiMap = new DualHashBidiMap<>();

    @Override
    public Class<?> loadTargetClass(String classTypeName, String version) throws ClassNotFoundException {
        // 当不存在key时直接查找相应class
        String key = generateKey(classTypeName, version);
        if (!bidiMap.containsKey(key)) {
            Class<?> target = Class.forName(classTypeName);
            register(target.getName(), target);
        }
        return (Class<?>) bidiMap.get(key);
    }

    @Override
    public String loadClassTypeName(Class<?> target) {
        if (!bidiMap.containsValue(target)) {
            register(target.getName(), target);
        }
        return ((String) bidiMap.getKey(target)).split("-")[0];
    }

    @Override
    public void register(String classTypeName, Class<?> targetType) {
        String version = DomainEventUtils.getEventVersion(targetType);
        String key = generateKey(classTypeName, version);
        bidiMap.put(key, targetType);
    }

    private String generateKey(String classType, String classVersion) {
        return String.format("%s-%s", classType, classVersion);
    }

}
